package com.hanbang.qzzds.utils.other;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.widget.Toast;

import com.hanbang.qzzds.appliction.MyApplication;
import com.hanbang.qzzds.utils.http.BitmapUtil;
import com.hanbang.qzzds.utils.ui.ToastUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import static com.hanbang.qzzds.appliction.MyApplication.myApp;


public class FileUtils {
    /**
     * 获取视频文件的一帧
     */
    public static Bitmap getVideoFrame(String path, int wDp, int hDp) {
        MediaMetadataRetriever media = new MediaMetadataRetriever();
        media.setDataSource(path);
        return BitmapUtil.zoomImage(media.getFrameAtTime(), ObjectUtils.dip2px(myApp, wDp), ObjectUtils.dip2px(myApp, hDp));
    }

    /**
     * 获取照片选择的文件路径
     */
    public static String getFileSelectPath(Intent data) {
        if (data == null || data.getData() == null) return null;
        return ObjectUtils.getPath(myApp, data.getData());
    }

    /**
     * 获取拍摄的文件的路径
     */
    public static String getPaiFilePath(Context context, String cachePath) {
        File fDir = new File(MyApplication.appSDCachePath);
        // 判断文件夹是否存在
        if (fDir.exists() || fDir.mkdirs()) {
            File cameraFile = new File(fDir, cachePath);
            // 判断文件时是否存在
            if (cameraFile.exists()) {
                return cameraFile.getPath();
            } else {
                ToastUtils.show(context, "获取失败！", Toast.LENGTH_SHORT);
            }
        } else {
            ToastUtils.show(context, "获取失败！", Toast.LENGTH_SHORT);
        }
        return null;
    }

    /**
     * 开启拍照
     */

    public static String startPaiZhao(Object context, int requestCode) {
        File fDir = new File(MyApplication.appSDCachePath);
        String cachePath = System.currentTimeMillis() + ".jpg";
        if (fDir.exists() || fDir.mkdirs()) {
            File cameraFile = new File(fDir, cachePath);
            if (!cameraFile.exists()) {
                try {
                    cameraFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile));
            if (context instanceof Activity) {
                ((Activity) context).startActivityForResult(intent, requestCode);
            } else if (context instanceof Fragment) {
                ((Fragment) context).startActivityForResult(intent, requestCode);
            } else {
                return "";
            }
            return cachePath;
        }
        return "";
    }

    /**
     * 开启文件选择
     */
    public static void startFileSelect(Object context, String Type, int requestCode) {
        Intent intent = new Intent();
        intent.setType(Type);
        intent.setAction(Intent.ACTION_GET_CONTENT);
        intent.putExtra("return-data", true);
        if (context instanceof Activity) {
            ((Activity) context).startActivityForResult(intent, requestCode);
        } else if (context instanceof Fragment) {
            ((Fragment) context).startActivityForResult(intent, requestCode);
        } else {
        }
    }

    // 获取ApiKey
    public static String getMetaValue(Context context, String metaKey) {
        Bundle metaData = null;
        String apiKey = null;
        if (context == null || metaKey == null) {
            return null;
        }
        try {
            ApplicationInfo ai = context.getPackageManager()
                    .getApplicationInfo(context.getPackageName(),
                            PackageManager.GET_META_DATA);
            if (null != ai) {
                metaData = ai.metaData;
            }
            if (null != metaData) {
                apiKey = metaData.getString(metaKey);
            }
        } catch (NameNotFoundException e) {

        }
        return apiKey;
    }

    public static String readInputStream(InputStream is) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int len = 0;
            byte[] buffer = new byte[1024];
            while ((len = is.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            is.close();
            baos.close();
            byte[] result = baos.toByteArray();
            return new String(result, "GB2312");
        } catch (Exception e) {
            e.printStackTrace();
            return "获取失败";
        }

    }

    public static String readInputStream(InputStream is, String coding) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int len = 0;
            byte[] buffer = new byte[1024];
            while ((len = is.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            is.close();
            baos.close();
            byte[] result = baos.toByteArray();
            return new String(result, coding);
        } catch (Exception e) {
            e.printStackTrace();
            return "获取失败";
        }

    }

    /*
     * 读取assets文件目录下的文件，以字符串返回
     */
    public static String readAssets(Context context, String name) {
        String resultString = "";
        InputStream inputStream = null;
        try {
            inputStream = context.getResources().getAssets().open(name);
            byte[] buffer = new byte[inputStream.available()];
            inputStream.read(buffer);
            resultString = new String(buffer);
        } catch (Exception e) {

        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return resultString;
    }

    /**
     * 复制单个文件
     *
     * @param oldPath String 原文件路径 如：c:/fqf.txt
     * @param newPath String 复制后路径 如：f:/fqf.txt
     * @return boolean
     */
    public static void copyFile(String oldPath, String newPath) {
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) { //文件存在时
                FileInputStream inStream = new FileInputStream(oldPath); //读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; //字节数 文件大小
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
        } catch (Exception e) {
            System.out.println("复制单个文件操作出错");
            e.printStackTrace();

        }

    }


}
